package com.css.zfzx.sjcj.modules.hddcGeophySvyFaultPoint.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcActiveFault.repository.entity.HddcActivefaultEntity;
import com.css.zfzx.sjcj.modules.hddcActiveFault.service.HddcActivefaultService;
import com.css.zfzx.sjcj.modules.hddcFaultSvyPoint.repository.entity.HddcFaultsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPoint.repository.entity.HddcGeologicalsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcGeophySvyFaultPoint.repository.HddcGeophysvyfaultpointNativeRepository;
import com.css.zfzx.sjcj.modules.hddcGeophySvyFaultPoint.repository.HddcGeophysvyfaultpointRepository;
import com.css.zfzx.sjcj.modules.hddcGeophySvyFaultPoint.repository.entity.HddcGeophysvyfaultpointEntity;
import com.css.zfzx.sjcj.modules.hddcGeophySvyFaultPoint.service.HddcGeophysvyfaultpointService;
import com.css.zfzx.sjcj.modules.hddcGeophySvyFaultPoint.viewobjects.HddcGeophysvyfaultpointQueryParams;
import com.css.zfzx.sjcj.modules.hddcGeophySvyFaultPoint.viewobjects.HddcGeophysvyfaultpointVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zhangcong
 * @date 2020-11-30
 */
@Service
public class HddcGeophysvyfaultpointServiceImpl implements HddcGeophysvyfaultpointService {

	@Autowired
    private HddcGeophysvyfaultpointRepository hddcGeophysvyfaultpointRepository;
    @Autowired
    private HddcGeophysvyfaultpointNativeRepository hddcGeophysvyfaultpointNativeRepository;
    @Autowired
    private HddcActivefaultService hddcActivefaultService;

    @Override
    public JSONObject queryHddcGeophysvyfaultpoints(HddcGeophysvyfaultpointQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcGeophysvyfaultpointEntity> hddcGeophysvyfaultpointPage = this.hddcGeophysvyfaultpointNativeRepository.queryHddcGeophysvyfaultpoints(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcGeophysvyfaultpointPage);
        return jsonObject;
    }


    @Override
    public HddcGeophysvyfaultpointEntity getHddcGeophysvyfaultpoint(String id) {
        HddcGeophysvyfaultpointEntity hddcGeophysvyfaultpoint = this.hddcGeophysvyfaultpointRepository.findById(id).orElse(null);
         return hddcGeophysvyfaultpoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeophysvyfaultpointEntity saveHddcGeophysvyfaultpoint(HddcGeophysvyfaultpointEntity hddcGeophysvyfaultpoint) {
        String uuid = UUIDGenerator.getUUID();
        hddcGeophysvyfaultpoint.setUuid(uuid);
        hddcGeophysvyfaultpoint.setCreateUser(PlatformSessionUtils.getUserId());
        hddcGeophysvyfaultpoint.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcGeophysvyfaultpoint.setIsValid("1");
        this.hddcGeophysvyfaultpointRepository.save(hddcGeophysvyfaultpoint);
        return hddcGeophysvyfaultpoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeophysvyfaultpointEntity updateHddcGeophysvyfaultpoint(HddcGeophysvyfaultpointEntity hddcGeophysvyfaultpoint) {
        UpdateUtil.copyNullProperties(hddcGeophysvyfaultpointRepository.findByUuidAndIsValid(hddcGeophysvyfaultpoint.getUuid(), "1"), hddcGeophysvyfaultpoint);
        hddcGeophysvyfaultpoint.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcGeophysvyfaultpoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcGeophysvyfaultpointRepository.save(hddcGeophysvyfaultpoint);
        return hddcGeophysvyfaultpoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcGeophysvyfaultpoints(List<String> ids) {
        List<HddcGeophysvyfaultpointEntity> hddcGeophysvyfaultpointList = this.hddcGeophysvyfaultpointRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcGeophysvyfaultpointList) && hddcGeophysvyfaultpointList.size() > 0) {
            for(HddcGeophysvyfaultpointEntity hddcGeophysvyfaultpoint : hddcGeophysvyfaultpointList) {
                hddcGeophysvyfaultpoint.setIsValid("0");
                hddcGeophysvyfaultpoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeophysvyfaultpoint.setUpdateTime(new Date());
                this.hddcGeophysvyfaultpointRepository.save(hddcGeophysvyfaultpoint);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcGeophysvyfaultpointQueryParams queryParams, HttpServletResponse response) {
        List<HddcGeophysvyfaultpointEntity> yhDisasterEntities = hddcGeophysvyfaultpointNativeRepository.exportYhDisasters(queryParams);
        List<HddcGeophysvyfaultpointVO> list=new ArrayList<>();
        for (HddcGeophysvyfaultpointEntity entity:yhDisasterEntities) {
            HddcGeophysvyfaultpointVO yhDisasterVO=new HddcGeophysvyfaultpointVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "地球物理探测断点-点", "地球物理探测断点-点", HddcGeophysvyfaultpointVO.class, "地球物理探测断点-点.xls", response);

    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcGeophysvyfaultpointVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcGeophysvyfaultpointVO.class, params);
            List<HddcGeophysvyfaultpointVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcGeophysvyfaultpointVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcGeophysvyfaultpointVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    @Override
    @Transactional
    public int dataQualityCheck() {
        List<HddcGeophysvyfaultpointEntity> listAll = hddcGeophysvyfaultpointRepository.findByAll();
        for (HddcGeophysvyfaultpointEntity b2All: listAll) {
            String str="";
            if (StringUtils.isEmpty(b2All.getTargetfaultname())) {
                continue;
            }
            HddcActivefaultEntity hddcActivefaultEntity =  hddcActivefaultService.findByName(b2All.getTargetfaultname());
            if (hddcActivefaultEntity==null){
                hddcGeophysvyfaultpointRepository.updateStatus("2","质检失败",b2All.getUuid());
                continue;
            }
            if (!hddcActivefaultEntity.getTopdepth().equals(b2All.getM0depth()) ) {
                str += "上断点埋深 [米]失败.";
            }
            if (!hddcActivefaultEntity.getFeature().equals(b2All.getFaulttype())) {
                str += "断层性质失败";
            }
            if(str.isEmpty()){
                str +="质检成功";
                hddcGeophysvyfaultpointRepository.updateStatus("1",str,b2All.getUuid());
            }else{
                hddcGeophysvyfaultpointRepository.updateStatus("2",str,b2All.getUuid());
            }
        }
        return 1;
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcGeophysvyfaultpointVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcGeophysvyfaultpointEntity yhDisasterEntity = new HddcGeophysvyfaultpointEntity();
            HddcGeophysvyfaultpointVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcGeophysvyfaultpoint(yhDisasterEntity);
        }
    }

}
